package com.css.dzj.dzjfxyj.modules.reply.service.Impl;

import com.css.dzj.dzjfxyj.common.util.Constant;
import com.css.dzj.dzjfxyj.common.util.R;
import com.css.dzj.dzjfxyj.common.util.ServiceUtil;
import com.css.dzj.dzjfxyj.modules.acquier.entity.JgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.entity.QJgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.service.AcquierService;
import com.css.dzj.dzjfxyj.modules.distribute.entity.JgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.entity.QJgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.service.DistributeService;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.JgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.QJgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.mapper.ReplyMapper;
import com.css.dzj.dzjfxyj.modules.reply.service.ReplyService;
import com.css.dzj.dzjfxyj.modules.reply.vo.ReplyVo.MainDistributeVo;
import com.css.dzj.dzjfxyj.modules.reply.vo.ReplyVo.ReplyVo;
import com.css.dzj.dzjfxyj.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    private ReplyMapper replyMapper;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    private AcquierService acquierService;

    @Autowired
    private DistributeService distributeService;

    @Autowired
    private ServiceUtil serviceUtil;

    @Autowired
    private HttpServletRequest request;

    @Override
    public QueryResults<JgFxyjWarningSignalEntity> getAllReply(Pageable pageable) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;

        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.dispenseState.eq(Constant.YIDISTRIBUTE));
        predicate = ExpressionUtils.and(predicate, q.overState.eq(Constant.DAIREPLY));
        return  jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    @Override
    public ReplyVo queryOne(String id) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        JgFxyjWarningSignalEntity fetchOne = jpaQueryFactory
                                            .selectFrom(q)
                                            .where(q.id.eq(id)
                                            //q..delFlag.eq(Constant.NO_DELETE)
                                            )
                                            .fetchOne();
        ReplyVo replyVo = new ReplyVo();
        replyVo.setRiskwarning(fetchOne);
        //replyVo.setJgFxyjWarningSignalEntity(fetchOne);
        QJgFxyjFeedbackEntity qreply = QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        List<JgFxyjFeedbackEntity> list = jpaQueryFactory
                .selectFrom(qreply)
                .where(qreply.taskId.eq(id))
                .orderBy(
                        // 根据创建日期，降序排序
                        qreply.createTime.desc()
                ).fetch();
        replyVo.setRiskwarningChildren(list);
        //replyVo.setJgFxyjFeedbackEntityList(list);
        return replyVo;
    }

    @Override
    @Transactional
    public String addReply(ReplyVo vo, HttpServletRequest request) {
        try {
            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String orgName = "";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                orgName = userInfo.getOrgName();
            }

            List<JgFxyjFeedbackEntity> list = vo.getRiskwarningChildren();
            JgFxyjWarningSignalEntity jws = vo.getRiskwarning();
            JgFxyjFenfaEntity jgFxyjFenfaEntity = distributeService.findByGetIdAndFenfaToOrg(jws.getId(), orgName);
            List<JgFxyjFeedbackEntity> listsave = new ArrayList<>();
            for(int i=0;i<list.size();i++){
                JgFxyjFeedbackEntity jfe = list.get(i);
                jfe.setCreateTime(new Date());
                jfe.setTaskId(jws.getId());
                if(jgFxyjFenfaEntity != null) {
                    jfe.setFbId(jgFxyjFenfaEntity.getId());
                }
                jfe.setCreatePreson(suserName);
                jfe.setResponseTime(new Date());
                listsave.add(jfe);
            }

            replyMapper.saveAll(listsave);
            updHuifuState(jws.getId());
            updFenFaState(jws.getId(),orgName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 修改回复状态
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R updHuifuState(String id) {
        try {
            if(!"".equals(id) && id!=null){
                QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
                jpaQueryFactory.update(q)
                        .set(q.revertState, Constant.YIREPLY).set(q.dealState,Constant.YIFANKUI)
                        .where(q.id.eq(id))
                        .execute();
                return R.ok();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public List<JgFxyjFeedbackEntity> queryByFbId(String fbId) {
        QJgFxyjFeedbackEntity q = QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        return jpaQueryFactory.selectFrom(q)
                .where(q.fbId.eq(fbId))
                .fetch();

    }

    public R updFenFaState(String id,String orgName) {
        try {
            if(!"".equals(id) && id!=null){
                QJgFxyjFenfaEntity q = QJgFxyjFenfaEntity.jgFxyjFenfaEntity;
                Predicate predicate = q.isNotNull().or(q.isNull());
                predicate = ExpressionUtils.and(predicate,q.getId.eq(id));
                predicate = ExpressionUtils.and(predicate,q.fenfaToOrg.eq(orgName));
                jpaQueryFactory.update(q)
                        .set(q.revertState, Constant.YIREPLY)
                        .where(predicate)
                        .execute();
                return R.ok();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    /**
     * 存在的问题，分发给哪个机构，哪个机构才能在待回复列表看到，目前的接口没有做处理
     * @param pageable
     * @param fxyjDomainId
     * @param fxyjTitle
     * @param fxyjLevel
     * @param fxyjObjectName
     * @param startTime
     * @param endTime
     * @param startTime1
     * @param endTime1
     * @return
     */
    @Override
    public QueryResults<MainDistributeVo> getPage(Pageable pageable, String fxyjDomainId, String fxyjTitle, String fxyjLevel, String fxyjObjectName, String startTime, String endTime, String startTime1, String endTime1) {
        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;

        QJgFxyjFenfaEntity fenfa = QJgFxyjFenfaEntity.jgFxyjFenfaEntity;

        //获取当前登录人机构
        String orgName = ServiceUtil.getOrgName(request);

        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (fxyjDomainId == null || fxyjDomainId.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (fxyjTitle == null || fxyjTitle.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (fxyjLevel == null || fxyjLevel.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (fxyjObjectName == null || fxyjObjectName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%"+fxyjObjectName.trim()+"%"));
        predicate = ExpressionUtils.and(predicate, q.dispenseState.eq(Constant.YIDISTRIBUTE));
        //predicate = ExpressionUtils.and(predicate, q.overState.eq(Constant.DAIREPLY));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            System.out.println();
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.getTime.between(startDate,endDate));
        }

        if((StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime1 + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
                endDate = sf.parse(endTime1 + " 23:59:59.999");
                System.out.println();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }
        predicate = ExpressionUtils.and(predicate, fenfa.fenfaToOrg.eq(orgName));
        predicate = ExpressionUtils.and(predicate,fenfa.overState.isNull());
        return jpaQueryFactory
                .select(Projections.bean(MainDistributeVo.class,
                        q.id,q.fxyjId,q.fxyjDomainId,q.fxyjModelId,q.fxyjAreaNumber,q.fxyjObjectType,q.fxyjObjectId
                        ,q.fxyjObjectName,q.fxyjPlatform,q.fxyjWeb,q.fxyjTransmitTime,q.yjbSendTime,q.getTime,q.operatePerson,q.disposeResult
                        ,q.disposeExplain,q.getState,q.dispenseState,q.dispensePerson,q.dispenseOrg
                        ,q.dispenseTime,q.createTime,q.createPreson,q.updateTime,q.updatePerson,q.operateOrg,q.fxyjTitle
                        ,q.fxyjLevel,q.fxyjAreaName,q.fxyjProps,q.fxyjDetailUrl,q.fxyjOthers,q.fxyjTime,q.fxyjDesc,q.dealState
                        ,fenfa.fenfaToOrg,fenfa.getId,fenfa.overState,fenfa.revertState)).
                from(q).
                innerJoin(fenfa).on(q.id.eq(fenfa.getId)).
                where(predicate).
                orderBy(q.createTime.desc()).
                offset(pageable.getOffset()).
                limit(pageable.getPageSize()).
                fetchResults();
    }

    /**
     * 通过风险预警线索唯一ID
     * 查询详细信息
     */
    @Override
    public ReplyVo queryAcquire(String id,String from,HttpServletRequest request) {
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String orgName = "";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();
            location = orgName.replace("地震局","");
            address = userInfo.getAddress();
        }
        ReplyVo replyVo = new ReplyVo();
        JgFxyjWarningSignalEntity acquire = acquierService.findById(id);
        JgFxyjFeedbackEntity reply = new JgFxyjFeedbackEntity();
        reply.setFxyjId(acquire.getFxyjId());
        reply.setFxyjObjectType(acquire.getFxyjObjectType());
        reply.setFxyjObjectId(acquire.getFxyjObjectId());
        reply.setFxyjOperator(suserName);
        reply.setFxyjOperatorType(orgName);
        List<JgFxyjFeedbackEntity> replys = queryList(acquire.getId());
        if (replys==null || replys.size()<=0){
            reply.setFxyjFeedbackId("001");
        }else {
           int fint = replys.size()+1;
           int g = fint/10;
           if (g==0){
               reply.setFxyjFeedbackId("00"+fint);
           }else {
               int s = g / 10;
               if (s == 0) {
                   reply.setFxyjFeedbackId("0" + fint);
               } else {
                   reply.setFxyjFeedbackId("" + fint);
               }
           }
        }
        if ("over".equals(from)){
            reply.setFxyjResult("3");
            reply.setFxyjEnd(new Date());
        }else {
            reply.setFxyjResult("2");
            reply.setResponseTime(new Date());
        }
        List<JgFxyjFeedbackEntity> list = new ArrayList<>();
        list.add(reply);
        replyVo.setRiskwarning(acquire);
        replyVo.setRiskwarningChildren(list);
        return replyVo;
    }

    @Override
    public List<JgFxyjFeedbackEntity> queryList(String id) {
        QJgFxyjFeedbackEntity qreply = QJgFxyjFeedbackEntity.jgFxyjFeedbackEntity;
        List<JgFxyjFeedbackEntity> list = jpaQueryFactory
                .selectFrom(qreply)
                .where(qreply.taskId.eq(id))
                .orderBy(
                        // 根据创建日期，降序排序
                        qreply.createTime.desc()
                ).fetch();
        return list;
    }

}
